#include "GLDriver.h"

namespace mp_gl
{

	GLDriver::GLDriver(
			bool enableLogicThread, 
			bool enableNetworkThread)
	{
		m_glApp = NULL;
		//m_errors = new ErrorHandler();
		m_threadPool = new ThreadPoolManager();

		if ( enableNetworkThread )
			m_networkThread = new NetworkThread();
		else
			m_networkThread = NULL;
		if ( enableLogicThread ) 
			m_logicThread = new LogicThread();
		else
			m_logicThread = NULL;

	}
		
	GLDriver::GLDriver(GLApp* app)
	{
		bool networkThreading;
		m_glApp = app;
		//m_errors = new ErrorHandler();
		m_threadPool = new ThreadPoolManager();

		if ( app != NULL )
			networkThreading = 
				app->IsNetworkingThreadEnabled();
#ifdef ENABLE_MULTITHREAD_BY_DEF
			networkThreading = true;
#else
			networkThreading = false;
#endif

		if ( networkThreading )
			m_networkThread = new NetworkThread();
		else
			m_networkThread = NULL;
		if ( networkThreading )
			m_logicThread = new LogicThread();
		else
			m_logicThread = NULL;
	}

	GLDriver::~GLDriver()
	{ 
		if (m_glApp != NULL) 
			delete m_glApp; 
	}

	int GLDriver::Run()
	{
		//m_errors->WriteError("[MPGL] Loading GLFW Libraries \n");

		//Initialize the error handler
		InitializeErrorHandler();

		//Initialize the GLFW library
		if (!glfwInit())
		{
			//m_errors->WriteError(
				//"GLDriver::Run - Could not Initialize GLFW");
			return -1;
		}

		//Initialize the thread pool
		InitializeThreadPool();

		//Initialize the application
		m_glApp->Initialize();
		m_glApp->LoadContent();

		//Add Threads before we start running
		if (m_logicThread != NULL)
			m_threadPool->AddThread(m_logicThread);
		if (m_networkThread != NULL)
		{
			//Link the network thread to the network manager
			// before starting.
			m_networkThread->SetNetworkManager(	
				m_glApp->GetNetworkManager());
			m_threadPool->AddThread(m_networkThread);
		}

		//Update the application
		while(m_glApp->IsRunning())
		{
			m_glApp->Update();
			if (m_logicThread == NULL)
				m_glApp->UpdateLogic();
			m_glApp->Draw();
		}

		//Stop operating threads after running
		m_logicThread->RequestStop();
		m_networkThread->RequestStop();

		//m_renderThread->RequestStop();
		m_glApp->UnloadContent();

		//Uninitialize the application
		m_glApp->Uninitialize();

		//Terminate the GLFW library and quit
		glfwTerminate();
		return 0;
	}
	
	void GLDriver::InitializeErrorHandler()
	{
		//Set the app to this error handler
		//m_glApp->SetErrorHandler(m_errors);
	}

	void GLDriver::InitializeThreadPool()
	{

	}

	void GLDriver::InitializeThreads()
	{

	}

}